import { Component, Prop } from 'vue-property-decorator';
import AbpBase from "@/lib/abpbase";
import ajax from '@/lib/ajax';
import AppConst from '@/lib/appconst';
import { saveFile, saveFileFromBase64 } from '@/lib/download';

@Component
export default class ImportMixin extends AbpBase {
  @Prop({ type: Boolean, default: false }) value: boolean;

  saving = false;
  apiServer = AppConst.remoteServiceBaseUrl;

  // TODO:
  importData: any;

  // TODO:
  async saveItem() {
    // const { schoolType, schoolCategory, runSchoolType } = this.school
    // this.school.schoolTypeName = (this.schoolTypes.find((t) => t.id === schoolType) || {})['name']
    // this.school.schoolCategoryName = (this.schoolCategories.find((t) => t.id === schoolCategory) || {})['name']
    // this.school.runSchoolTypeName = (this.runTypes.find((t) => t.id === runSchoolType) || {})['name']
    // await this.$store.dispatch({
    //   type: 'school/create',
    //   data: this.school
    // });

    return new Promise<any>(() => false);
  }
  save() {
    const importForm = this.$refs.importForm as any;
    if (!!importForm) {
      importForm.validate(async (valid: boolean) => {
        if (valid) {
			this.maskShow();
          try {
            this.saving = true;
            const resetFlag = await this.saveItem()
            this.$Message.success('导入成功')
            if (!!importForm && !!resetFlag) {
              importForm.resetFields();
            }
            this.$emit('save-success');
            this.$emit('input', false);
          } catch(err) {
            this.$Message.error('导入失败')
          } finally {
            this.saving = false;
			this.maskHide();
          }
        }
      })
    }
  }
  cancel() {
    (this.$refs.importForm as any).resetFields();
    this.$emit('input', false);
  }

  // TODO
  async onHide() {
    // this.$store.commit('school/edit', null);
    // this.school = new CreateOrUpdateSchoolInfo();
  }
  // TODO
  async onShow() {
    // this.getCities()
    // await this.getSchoolTypes()
    // await this.getSchoolCategories()
    // await this.getRunTypes()
    // if (!!this.$store.state.school.editSchool) {
    //   ajax.get('/api/services/app/SchoolInformation/GetSchoolInformationForEdit', {
    //     params: {
    //       Id: this.$store.state.school.editSchool.id,
    //     }
    //   }).then((res) => {
    //     if (res.data.success) {
    //       Object.assign(this.school, res.data.result.schoolInforOutput)
    //     }
    //   });
    // }
  }
  async visibleChange(value: boolean) {
    if (!value) {
      this.importData = {};
      await this.onHide();
    } else {
      await this.onShow();
    }
    this.$emit('input', value);
  }

  // TODO
  async createdInit() {
    
  }
  async created() {
    await this.createdInit()
  }

	afterUpload(filePath) {
		//console.log('filePath',filePath);
	}
	
  // TODO
  beforeUpload(file) {
	  console.log('file',file);
    let fd = new FormData()
    fd.append('file', file)
    ajax.post('/api/File/UploadSingleFile', fd)
      .then((res) => {
        if (res.data.success) {
          const { filePath, ordinName, md5 } = res.data.result
          Object.assign(this.importData, {
            filePath,
            md5,
            excelFile: ordinName,
            file,
          })
		  this.afterUpload(filePath);
        } else if (res.data.error) {}
      })

    return false
  }

  // TODO
  importRules = {}


  // TODO
  templatePath = ''
  templateName = ''
  
  downloadTemplate() {
    if (!!this.templatePath) {
      let filename = /.*\.xlsx$/.test(this.templatePath) ? 'template.xlsx' : 'template.xls'
      saveFile(`${this.apiServer}${this.templatePath}`, this.templateName || filename)
    }
  }
  //zhang↓
  interval = 0
  maskShow() {
	  (this.$Spin as any).show({
	  	render: (h) => {
	  		return h('div', [
	  			h('img', {
	  				style: {
	  					width: "40px",
	  					height: "40px"
	  				},
	  				attrs: {
	  					src: './img/loading.gif'//../public/img
	  				}
	  			}),
	  			h('div',{'class': 'waitingMsgContioner'},
	  			[
	  				h('p',{'class':'waitingMsg'},'正在为您导入数据···'),
	  				h('p',{'class':'waitingMsg'},'数据正在排队上传中···'),
	  				h('p',{'class':'waitingMsg'},'正在努力导入中···'),
	  				h('p',{'class':'waitingMsg'},'坚持就是胜利，马上就好啦···')
	  			])
	  		]);
	  	}
	  });
	  this.interval = setInterval(() => {
	  	document.getElementsByClassName("waitingMsgContioner")[0].appendChild(document.querySelector('.waitingMsg'));
	  }, 5000);
  }
  
  maskHide() {
	  (this.$Spin as any).hide();
	  clearInterval(this.interval);
  }
  //zhang↑
}